<template>
  <a-modal
    v-model:visible="visible"
    :width="600"
    centered
    :label-col="{ style: { width: '125px' } }"
    :mask-closable="false"
    class="word-gift"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-spin :spinning="submitting">
      <a-tabs v-model:activeKey="active">
        <a-tab-pane
          :key="GiftKindEnum.Gift"
          tab="自填赠词"
          v-if="record.productId !== ProductEnum.CiBao && record.productId !== ProductEnum.CBYXB"
        >
          <a-alert message="请注意！" type="warning" show-icon>
            <template #description>
              <p v-if="record.productId === ProductEnum.BWSD || record.productId === ProductEnum.BWSDYXB">
                <span>当前可用赠词：</span>
                <span v-if="Gift && Gift.pcNumber >= 0">PC端{{ Gift.pcNumber }}个</span>
                <span v-if="Gift && Gift.wapNumber >= 0"> 手机端{{ Gift.wapNumber }}个</span>
                <span>，赠送的关键词仅支持一次添加，确认提交后将不能再修改或补充，请谨慎操作。</span>
              </p>
              <p v-else>
                当前可用赠词数为{{
                  giftFormFields.wordNum
                }}个。赠送的关键词仅支持一次添加，确认提交后将不能再修改或补充，请谨慎操作。
              </p>
            </template>
          </a-alert>
          <Divider></Divider>
          <table-toolbar title="赠词列">
            <span></span>
          </table-toolbar>
          <a-form ref="FormUpdateRef" :model="giftFormFields">
            <word-gift v-model:data="giftFormFields" :record="record" @on-add="handleWordAdd" />
          </a-form>
        </a-tab-pane>
        <a-tab-pane
          :key="GiftKindEnum.Composable"
          tab="组合赠词"
          v-if="record.productId !== ProductEnum.BWSD && record.productId !== ProductEnum.BWSDYXB"
        >
          <a-form
            hide-required-mark
            :model="composableState"
            :label-col="{ style: { width: '90px' } }"
            :wrapper-col="{ span: 18 }"
            ref="FormComposableRef"
          >
            <word-composable
              ref="WordComposableRef"
              v-model:data="composableFields"
              :visible="visible"
              :record="record"
            />
          </a-form>
        </a-tab-pane>
        <a-tab-pane
          :key="GiftKindEnum.Edit"
          tab="配置赠词数量"
          v-if="
            hasPermission([OPERATION]) &&
            record.productId !== ProductEnum.CiBao &&
            record.productId !== ProductEnum.CBYXB &&
            record.productId !== ProductEnum.BWSD &&
            record.productId !== ProductEnum.BWSDYXB
          "
        >
          <div style="padding: 20px">
            <a-form hide-required-mark ref="ConfigurationGiftRef" :model="configurationGift">
              <a-form-item
                label="自填赠词数量"
                name="wordNumSum"
                :rules="{ required: true, message: '请输入自填赠词数量', trigger: 'blur' }"
              >
                <a-button type="link">
                  <MinusSquareOutlined style="font-size: 18px" @click="reduceWordNumSum" />
                </a-button>
                <a-input-number style="width: 70%" v-model:value="configurationGift.wordNumSum" :min="0" />
                <a-button type="link">
                  <PlusSquareOutlined style="font-size: 18px" @click="addWordNumSum" />
                </a-button>
              </a-form-item>
              <a-form-item
                label="组合赠词数量"
                name="combinedWordNumSum"
                :rules="{ required: true, message: '请输入组合赠词数量', trigger: 'blur' }"
              >
                <a-button type="link">
                  <MinusSquareOutlined style="font-size: 18px" @click="reducecombinedWordNumSum" />
                </a-button>
                <a-input-number style="width: 70%" v-model:value="configurationGift.combinedWordNumSum" :min="0" />
                <a-button type="link">
                  <PlusSquareOutlined style="font-size: 18px" @click="addcombinedWordNumSum" />
                </a-button>
              </a-form-item>
            </a-form>
          </div>
        </a-tab-pane>
      </a-tabs>
    </a-spin>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { useVModel } from '@vueuse/core'
import { FormInstance, message } from 'ant-design-vue'
import { MinusSquareOutlined, PlusSquareOutlined } from '@ant-design/icons-vue'
import WordGift from '@/views/promotion/components/WordGift.vue'
import TableToolbar from '@/components/table-toolbar/index.vue'
import Divider from '@/components/divider/index.vue'
import { FreeWord } from '@/services/promotion/updateFreeWord'
import WordComposable from '@/views/promotion/components/WordComposable.vue'
import type { Promotion } from '@/core/interfaces/promotion'
import { ComposableState, GiftKindEnum } from '@/views/promotion/interface'
import type { ConfigurationGiftType } from '@/services/promotion/editConfigurationGift'
import editConfigurationGift from '@/services/promotion/editConfigurationGift'
import { hasPermission } from '@/utils/permission'
import { AuthEnum } from '@/core/enums/auth'
import type { OnlineActivityInfo } from '@/services/promotion/checkOnlineActivity'
import { ProductEnum } from '@/core/enums/platform'

const { OPERATION } = AuthEnum

interface Props {
  show: boolean
  submitting: boolean
  giftFields: {
    freeWords: FreeWord[]
    wordNum: number
  }
  composableState: ComposableState
  record: Partial<Promotion>
  activeKey: GiftKindEnum
  ConfigurationGift: ConfigurationGiftType
  Gift?: OnlineActivityInfo
}

interface Emits {
  (e: 'on-submit'): void
  (e: 'on-add'): void
  (e: 'on-hide'): void
  (e: 'loadPromotionList'): void
}

defineOptions({
  name: 'WordGiftKind'
})

const props = withDefaults(defineProps<Props>(), {
  show: false,
  submitting: false
})

const emit = defineEmits<Emits>()
const giftFormFields = useVModel(props, 'giftFields')
const composableFields = useVModel(props, 'composableState')
const active = useVModel(props, 'activeKey')
const visible = useVModel(props, 'show')
const validating = ref(false)
const FormUpdateRef = ref<FormInstance>()
const FormComposableRef = ref<FormInstance>()
const ConfigurationGiftRef = ref<FormInstance>()
const WordComposableRef = ref<InstanceType<typeof WordComposable>>()
function handleSubmit() {
  validating.value = true
  if (active.value === GiftKindEnum.Edit) {
    subConfigurationGift()
  } else if (active.value === GiftKindEnum.Gift) {
    validWordUpdater()
  } else {
    validWordComposable()
  }
}
const checkWords = () => {
  const { record, Gift } = props

  if (record.productId === ProductEnum.BWSD || record.productId === ProductEnum.BWSDYXB) {
    //校验赠词数量
    const pcNumber = giftFormFields.value.freeWords.filter((item) => item.clientType === 0)
    const wapNumber = giftFormFields.value.freeWords.filter((item) => item.clientType === 1)

    if (Gift.pcNumber === undefined && pcNumber.length > 0) {
      message.error(`词选择错误：当前套餐仅支持手机端类型词`)
      return false
    }
    if (Gift.wapNumber === undefined && wapNumber.length > 0) {
      message.error(`词选择错误：当前套餐仅支持PC端类型词`)
      return false
    }

    if (Gift?.pcNumber && pcNumber.length > Gift.pcNumber) {
      message.error(`限制PC端赠词最大数量${Gift?.pcNumber}个`)
      return false
    }
    if (Gift?.wapNumber && wapNumber.length > Gift.wapNumber) {
      message.error(`限制手机端赠词最大数量${Gift?.wapNumber}个`)
      return false
    }
    return true
  }
  return true
}

function validWordUpdater() {
  FormUpdateRef.value
    ?.validate()
    .then(() => {
      if (checkWords()) {
        emit('on-submit')
      }
    })
    .finally(() => {
      validating.value = false
    })
}

function validWordComposable() {
  if (composableFields.value.result.length === 0) {
    return message.error('请选择组合词')
  }

  FormComposableRef.value
    ?.validate()
    .then(() => {
      emit('on-submit')
    })
    .finally(() => {
      validating.value = false
    })
}

function handleCancel() {
  emit('on-hide')
}

function resetFormFields() {
  FormUpdateRef.value?.resetFields()
  FormComposableRef.value?.resetFields()
  ConfigurationGiftRef.value?.resetFields()
  WordComposableRef.value?.bwAreaReset()
}

function handleWordAdd() {
  emit('on-add')
}

// 配置赠词

const configurationGift = useVModel(props, 'ConfigurationGift')

const [, editConfigurationGiftFn, editLoading] = editConfigurationGift()
async function subConfigurationGift() {
  ConfigurationGiftRef.value
    ?.validate()
    .then(async () => {
      const [err, res] = await editConfigurationGiftFn({
        ...configurationGift.value
      })
      if (err) {
        message.error(err.message || '配置失败')
      } else {
        message.success(res.data.msg || '配置成功')
        handleCancel()
        visible.value = false
        emit('loadPromotionList')
      }
    })
    .finally(() => {
      validating.value = false
    })
}

function reduceWordNumSum() {
  if (configurationGift.value.wordNumSum! <= 0) return
  configurationGift.value.wordNumSum!--
}
function addWordNumSum() {
  configurationGift.value.wordNumSum!++
}
function reducecombinedWordNumSum() {
  if (configurationGift.value.combinedWordNumSum! <= 0) return
  configurationGift.value.combinedWordNumSum!--
}
function addcombinedWordNumSum() {
  configurationGift.value.combinedWordNumSum!++
}

defineExpose({
  resetFormFields
})
</script>

<style lang="scss" scoped>
.word-gift {
  .ant-modal-body {
    padding-top: 0 !important;
  }

  .ant-tabs-tab-btn {
    font-size: 15px;
  }
}

.tip {
  color: red;
  padding: 10px 50px 0;
  margin: 0;
}
</style>
